package com.ggy.tuibi.service.yuanqimoguicheng.Impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ggy.tuibi.dao.yuanqimoguicheng.YuanQiMoGuiChengUserDAO;
import com.ggy.tuibi.entity.yuanqimoguicheng.Machine;
import com.ggy.tuibi.entity.yuanqimoguicheng.YuanQiMoGuiChengUser;
import com.ggy.tuibi.service.yuanqimoguicheng.YuanQiMoGuiChengService;
import com.ggy.tuibi.utils.DoRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
@Slf4j
public class YuanQiMoGuiChengServiceImpl extends ServiceImpl<YuanQiMoGuiChengUserDAO, YuanQiMoGuiChengUser> implements YuanQiMoGuiChengService {

    @Autowired
    private DoRequestUtils doRequestUtils;

    @Override
    public String getJiQiInFo(String userId, String groupId) {
        HttpRequest request = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/machine_getMachineList.do?user_id=" + userId + "&group_id=" + groupId + "&page=0&IMEI=6e3dd51a7c754572be1b9e7885aa3234");
        HttpResponse response = request.execute();
        String body = response.body();
        System.out.println(body);
        return null;
    }

    @Override
    public YuanQiMoGuiChengUser enroll() {
        //o6wJF6qNZhWeqbnW1oVUzLgedqzb
        //&user_openid=omqNB50q5GWZNgg7HmJeVynrVMpU
        YuanQiMoGuiChengUser one = new YuanQiMoGuiChengUser();
        String userUnionId = "";
        do {
            userUnionId = getUserUnionId();
            one = this.getOne(new LambdaQueryWrapper<YuanQiMoGuiChengUser>().eq(YuanQiMoGuiChengUser::getUser_union_id, userUnionId));
        } while (ObjectUtil.isNotEmpty(one));
        String userNikeName = getUserName();


        String createUserUrl = "http://www.douyuewang.com/YuanQiJieJi_Web/login_register_wechat.do?user_union_id=" + userUnionId + "&user_nickname=" + userNikeName;
        String body = doRequestUtils.request(Method.POST, createUserUrl, null, null);
        log.info("enroll:  " + body);
        JSONObject bodyJsonObject = JSONUtil.parseObj(body);
        String code = bodyJsonObject.getStr("code");
        if ("200".equals(code)) {
            String data = bodyJsonObject.getStr("data");
            YuanQiMoGuiChengUser yuanQiMoGuiChengUser = JSONUtil.toBean(data, YuanQiMoGuiChengUser.class);
            yuanQiMoGuiChengUser.setUser_union_id(userUnionId);
            yuanQiMoGuiChengUser.setIs_sign_in("0");
            yuanQiMoGuiChengUser.setIs_shimobun("0");
            this.save(yuanQiMoGuiChengUser);
            return yuanQiMoGuiChengUser;
        }
        log.info("创建用户失败");
        return null;
    }

    @Override
    public Boolean yuanQiQianDao() {
//        List<YuanQiMoGuiChengUser> userList = this.list(new LambdaQueryWrapper<YuanQiMoGuiChengUser>()
//                .eq(YuanQiMoGuiChengUser::getIs_sign_in, "0"));
//        for (int i = 0; i < userList.size(); i++) {
//
//            ExecutorService executorService = Executors.newCachedThreadPool();
//            List<Runnable> taskList = new ArrayList<>();
//            for (int j = 0; i < 300; i++) {
//                int finalI = j;
//                taskList.add(() -> qiandao(userList.get(finalI)));
//            }
//            for (Runnable runnable : taskList) {
//                executorService.submit(runnable);
//            }
//
//            executorService.shutdown();
//
//
//            try {
//                Thread.sleep(60000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
        this.qiandao(null);
        return true;
    }

    private void qiandao(YuanQiMoGuiChengUser user){
        String qiandaoUrl = "http://www.douyuewang.com/YuanQiJieJi_Web/userIndex_updateUserSign.do?user_id=" + "tqdgRUb_3hcUCUpRI70jkRuhKCB7ohYh" + "&cumulative_id=7";
        HttpResponse response = HttpUtil.createPost(qiandaoUrl).execute();
//        String body = doRequestUtils.request(Method.POST, qiandaoUrl, null, null);
        log.info("签到响应:{}", response.body());
    }


    @Override
    public YuanQiMoGuiChengUser getUserByUserIdApi(String userId) {
        String body = HttpUtil.createGet("http://www.douyuewang.com/YuanQiJieJi_Web/userIndex_getUserPersonal.do?user_id=" + userId).execute().body();
        log.info("getUserByUserIdApi : " + body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String code = jsonObject.getStr("code");
        if ("200".equals(code)) {
            String data = jsonObject.getStr("data");
            String userMap = JSONUtil.parseObj(data).getStr("userMap");
            YuanQiMoGuiChengUser yuanQiMoGuiChengUser = JSONUtil.toBean(userMap, YuanQiMoGuiChengUser.class);
            return yuanQiMoGuiChengUser;
        }
        return null;
    }

    @Override
    public void shangJiFenXia(String jiQiName) {
        List<YuanQiMoGuiChengUser> userList = this.list(new LambdaQueryWrapper<>());
        List<Machine> machineList = this.getMachineList();
        Machine jiQi = machineList.stream().filter(machine -> jiQiName.equals(machine.getMachine_name())).distinct().collect(Collectors.toList()).get(0);
        for (int i = 0; i < userList.size(); i++) {
            YuanQiMoGuiChengUser user = userList.get(i);
            jiQi = getMachineAliasByMachineId(jiQi, user);
            String machinePrice = jiQi.getMachine_price();
            String userCost = user.getUser_cost();
            int j = Integer.valueOf(userCost) / Integer.valueOf(machinePrice);
            this.shangJi(user, jiQi);
            for (int k = 0; k < j; k++) {
                this.shangFen(user, jiQi);
            }
            this.xiaJi(user, jiQi);
        }
    }

    @Override
    public Machine getMachineAliasByMachineId(Machine jiQi, YuanQiMoGuiChengUser user) {
        HttpRequest request = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/doll_findMachineById.do?user_code=" + user.getUser_code() + "&machine_id=" + jiQi.getMachine_id());
        HttpResponse response = request.execute();
        String body = response.body();
        log.info("getMachineAliasByMachineId:" + body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if ("200".equals(jsonObject.getStr("code"))) {
            String data = jsonObject.getStr("data");
            String machineAlias = JSONUtil.parseObj(data).getStr("machine_alias");
            jiQi.setMachine_alias(machineAlias);
        }
        return jiQi;
    }

    @Override
    public void updateUserCost() {
        List<YuanQiMoGuiChengUser> userList = this.list();
        userList.forEach(user -> {

            String body = HttpUtil.createGet("http://www.douyuewang.com/YuanQiJieJi_Web/userIndex_getUserPersonal.do?user_id=" + user.getUser_id()).execute().body();
            log.info("updateUserCost: " + body);
            JSONObject jsonObject = JSONUtil.parseObj(body);
            if ("200".equals(jsonObject.getStr("code"))) {
                String data = jsonObject.getStr("data");
                JSONObject dataJsonObject = JSONUtil.parseObj(data);
                String userMap = dataJsonObject.getStr("userMap");
                JSONObject userMapJson = JSONUtil.parseObj(userMap);
                String userCost = userMapJson.getStr("user_cost");
                user.setUser_cost(userCost);
                this.update(user, new LambdaQueryWrapper<YuanQiMoGuiChengUser>().eq(YuanQiMoGuiChengUser::getUser_id, user.getUser_id()));
            }

        });
    }

    @Override
    public String qiehuan(String jiQiName,String mainUserId,String mainUserCode,String sourceUserId) {
        YuanQiMoGuiChengUser sourceUser = this.getOne(new LambdaQueryWrapper<YuanQiMoGuiChengUser>().eq(YuanQiMoGuiChengUser::getUser_id, sourceUserId));
        YuanQiMoGuiChengUser mainUser = new YuanQiMoGuiChengUser();
        mainUser.setUser_id(mainUserId);
        mainUser.setUser_code(mainUserCode);

        List<Machine> machineList = this.getMachineList();
        Machine jiQi = machineList.stream().filter(machine -> jiQiName.equals(machine.getMachine_name())).distinct().collect(Collectors.toList()).get(0);
        jiQi = getMachineAliasByMachineId(jiQi, sourceUser);
        this.xiaJi(mainUser,jiQi);
        this.shangJi(mainUser,jiQi);
        return "ok";
    }

    @Override
    public List<Machine> getMachineList() {
        String groupBody = HttpUtil.createGet("http://www.douyuewang.com/YuanQiJieJi_Web/machine_getMachineGroup.do").execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(groupBody);
        if (!"200".equals(jsonObject.getStr("code"))) {
            return null;
        }
        String data = jsonObject.getStr("data");
        String groupListStr = JSONUtil.parseObj(data).getStr("groupList");
        JSONArray groupList = JSONUtil.parseArray(groupListStr);

        List<Machine> machineList = new ArrayList<>();

        for (int i = 0; i < groupList.size(); i++) {
            Object object = groupList.get(i);
            String groupId = JSONUtil.parseObj(JSONUtil.toJsonStr(object)).getStr("group_id");
            HttpRequest request = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/machine_getMachineList.do?user_id=XKYtXguksCGxVRyNkJch8K_qw2Gbw41G&group_id=" + groupId + "&page=0");
            HttpResponse response = request.execute();
            String body = response.body();
            JSONObject bodyJsonObject = JSONUtil.parseObj(body);
            if (!"200".equals(bodyJsonObject.getStr("code"))) {
                break;
            }
            String dataM = bodyJsonObject.getStr("data");
            String machineListStr = JSONUtil.parseObj(dataM).getStr("machineList");
            JSONArray jsonArray = JSONUtil.parseArray(machineListStr);
            jsonArray.forEach(json -> machineList.add(JSONUtil.toBean(JSONUtil.toJsonStr(json), Machine.class)));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return machineList;
    }

    @Override
    public void shangJi(YuanQiMoGuiChengUser user, Machine machine) {
        //绑定
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_code", user.getUser_code());
        requestMap.put("user_id", user.getUser_id());
        requestMap.put("machine_group_num", machine.getMachine_group_num());
        requestMap.put("machine_id", machine.getMachine_id());
        requestMap.put("state", "2");
        HttpRequest bindRequest = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/doll_updateDollData.do?mapStr=" + JSONUtil.toJsonStr(requestMap));
        HttpResponse bindResponse = bindRequest.execute();
        log.info("绑定: " + bindResponse.body());

        //上机
        requestMap.put("state", "1");
        HttpRequest shangRequest = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/doll_updateDollData.do?mapStr=" + JSONUtil.toJsonStr(requestMap));
        HttpResponse shangResponse = shangRequest.execute();
        log.info("上机: " + shangResponse.body());
    }

    @Override
    public void xiaJi(YuanQiMoGuiChengUser user, Machine machine) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_code", user.getUser_code());
        requestMap.put("user_id", user.getUser_id());
        requestMap.put("machine_group_num", machine.getMachine_group_num());
        requestMap.put("machine_id", machine.getMachine_id());
        requestMap.put("state", "-2");
        HttpRequest xiaRequest = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/doll_updateDollData.do?mapStr=" + JSONUtil.toJsonStr(requestMap));
        HttpResponse response = xiaRequest.execute();
        log.info("下机: " + response.body());
    }

    @Override
    public void shangFen(YuanQiMoGuiChengUser user, Machine machine) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_code", user.getUser_code());
        requestMap.put("user_id", user.getUser_id());
        requestMap.put("machine_alias", machine.getMachine_alias());
        requestMap.put("machine_id", machine.getMachine_id());
        requestMap.put("message", "51");
        HttpRequest request = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/doll_WanShengYe.do?mapStr=" + JSONUtil.toJsonStr(requestMap));
        HttpResponse response = request.execute();
        log.info("上分: " + response.body());
    }


    private String getUserUnionId() {
        int length = 28;
        char[] chars = new char[length];
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int randomNumber = random.nextInt(62); // 生成0到61之间的随机数

            if (randomNumber < 10) {
                chars[i] = (char) (randomNumber + '0'); // 数字0到9对应的ASCII码为48到57
            } else if (randomNumber < 36) {
                chars[i] = (char) (randomNumber - 10 + 'A'); // 大写字母A到Z对应的ASCII码为65到90
            } else {
                chars[i] = (char) (randomNumber - 36 + 'a'); // 小写字母a到z对应的ASCII码为97到122
            }
        }
        log.info("生成的unionId:{}", new String(chars));
        System.out.println(new String(chars));
        return new String(chars);
    }

    public String getUserName() {
        String wangMingDaQuan = FileUtil.readString("D:\\java-projec\\study\\tuibi\\src\\main\\java\\com\\ggy\\tuibi\\file\\wangmingdaquannew.json", StandardCharsets.UTF_8);
        JSONArray jsonArray = JSONUtil.parseArray(wangMingDaQuan);
        Random random = new Random();
        int i = random.nextInt(jsonArray.size() - 1);
        String name = jsonArray.getJSONObject(i).getStr("name");
        jsonArray.remove(i);
        FileUtil.writeString(JSONUtil.toJsonStr(jsonArray), "D:\\java-projec\\study\\tuibi\\src\\main\\java\\com\\ggy\\tuibi\\file\\wangmingdaquannew.json", StandardCharsets.UTF_8);
        log.info("获取的name");
        return name;
    }

    public static void main(String[] args) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_code", "4279006");
        requestMap.put("user_id", "MqRZ5EqvvQXJVOF7QoTkfSuGZdWN00MX");
        requestMap.put("machine_group_num", 400);
        requestMap.put("machine_id", "20221206102140643");
        requestMap.put("state", "-2");
        HttpRequest xiaRequest = HttpUtil.createPost("http://www.douyuewang.com/YuanQiJieJi_Web/doll_updateDollData.do?mapStr=" + JSONUtil.toJsonStr(requestMap));
        HttpResponse response = xiaRequest.execute();
        log.info("下机: " + response.body());
    }

}
